package com.hyjiacan.apps.audionly.ui

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hyjiacan.apps.audionly.R
import com.hyjiacan.apps.audionly.databinding.ActivityMainBinding
import com.hyjiacan.apps.audionly.ui.viewmodel.MainViewModel

/**
 * 主界面Activity
 */
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    // 权限请求码
    private val REQUEST_STORAGE_PERMISSION = 100

    // 需要请求的权限
    private val requiredPermissions = arrayOf(
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        // 初始化ViewModel
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        // 检查并请求权限
        checkAndRequestPermissions()

        // 设置导入按钮点击事件
        binding.importBtn.setOnClickListener {
            // 打开相册
            openGallery()
        }

        // 观察视频文件列表
        viewModel.videoFiles.observe(this) {
            // 更新UI
            // 这里只是示例，实际应用中需要更新RecyclerView等UI组件
        }
    }

    // 检查并请求权限
    private fun checkAndRequestPermissions() {
        // 对于Android 13及以上版本，READ_EXTERNAL_STORAGE已被细分为READ_MEDIA_VIDEO等
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.READ_MEDIA_VIDEO
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(android.Manifest.permission.READ_MEDIA_VIDEO),
                    REQUEST_STORAGE_PERMISSION
                )
            } else {
                // 权限已授予
                setupUI()
            }
        } else {
            // 对于Android 12及以下版本
            val missingPermissions = requiredPermissions.filter {
                ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
            }

            if (missingPermissions.isNotEmpty()) {
                ActivityCompat.requestPermissions(
                    this,
                    missingPermissions.toTypedArray(),
                    REQUEST_STORAGE_PERMISSION
                )
            } else {
                // 权限已授予
                setupUI()
            }
        }
    }

    // 设置UI
    private fun setupUI() {
        // 设置导入按钮点击事件
        binding.importBtn.setOnClickListener {
            // 打开相册
            openGallery()
        }

        // 观察视频文件列表
        viewModel.videoFiles.observe(this) {
            // 更新UI
            // 这里只是示例，实际应用中需要更新RecyclerView等UI组件
        }
    }

    // 打开相册
    private fun openGallery() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "video/*"
        startActivityForResult(intent, 1001)
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                // 所有权限都已授予
                setupUI()
            } else {
                // 权限被拒绝
                Toast.makeText(
                    this,
                    "需要存储权限才能使用应用",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            data?.data?.let {
                // 获取视频文件路径
                val videoPath = getRealPathFromURI(it)
                if (videoPath != null) {
                    // 导航到参数设置界面
                    val intent = Intent(this, ParamSettingActivity::class.java)
                    intent.putExtra("video_path", videoPath)
                    startActivity(intent)
                }
            }
        }
    }

    // 从Uri获取真实文件路径
    private fun getRealPathFromURI(uri: android.net.Uri): String? {
        val projection = arrayOf(android.provider.MediaStore.Video.Media.DATA)
        val cursor = contentResolver.query(uri, projection, null, null, null)
        return cursor?.use {
            if (it.moveToFirst()) {
                val columnIndex = it.getColumnIndexOrThrow(android.provider.MediaStore.Video.Media.DATA)
                it.getString(columnIndex)
            } else {
                null
            }
        }
    }
}